package com.example.kafkaproducer.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.KafkaAdmin;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: wukangrong
 * @date: 2021/1/29 15:50
 * @description:
 */
@Configuration
@Slf4j
public class TopicConfig {

    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServer;

    @Value("${kafka.custom.topic.name}")
    private String topicName;

    /**
     * 创建TopicName为topic.quick.initial的Topic并设置分区数为3以及副本数为2
     */
    @Bean
    public NewTopic initialTopic() {
        log.info("创建topic中, {}", topicName);
        return new NewTopic(topicName, 3, (short) 2);
    }


    /**
     * 创建一个kafka管理类，相当于rabbitMQ的管理类rabbitAdmin,没有此bean无法自定义的使用adminClient创建topic
     */
    @Bean
    public KafkaAdmin kafkaAdmin() {
        Map<String, Object> props = new HashMap<>(2);
        props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServer);
        return new KafkaAdmin(props);
    }

    /**
     *  afka客户端，在spring中创建这个bean之后可以注入并且创建topic
     */
    @Bean
    public AdminClient adminClient() {
        return AdminClient.create(kafkaAdmin().getConfigurationProperties());
    }
}
